package com.lhj.xxsc.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lhj.xxsc.product.entity.SkuImagesEntity;
import com.lhj.xxsc.product.entity.SpuInfoDescEntity;
import com.lhj.xxsc.product.feign.SeckillFeignService;
import com.lhj.xxsc.product.service.*;
import com.lhj.xxsc.product.vo.SeckillInfoVo;
import com.lhj.xxsc.product.vo.SkuItemSaleAttrVo;
import com.lhj.xxsc.product.vo.SkuItemVo;
import com.lhj.xxsc.product.vo.SpuItemAttrGroupVo;
import com.xxsc.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxsc.common.utils.PageUtils;
import com.xxsc.common.utils.Query;

import com.lhj.xxsc.product.dao.SkuInfoDao;
import com.lhj.xxsc.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

	@Autowired
	SpuInfoDescService spuInfoDescService;

	@Autowired
	SkuImagesService skuImagesService;

	@Autowired
	AttrGroupService attrGroupService;

	@Autowired
	SkuSaleAttrValueService skuSaleAttrValueService;

	@Autowired
	ThreadPoolExecutor executor;

	@Autowired
	SeckillFeignService seckillFeignService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<SkuInfoEntity> page = this.page(
				new Query<SkuInfoEntity>().getPage(params),
				new QueryWrapper<SkuInfoEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
		this.baseMapper.insert(skuInfoEntity);
	}

	@Override
	public PageUtils queryPageByCondition(Map<String, Object> params) {
		QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
		/**
		 * key:
		 * catelogId: 0
		 * brandId: 0
		 * min: 0
		 * max: 0
		 */
		String key = (String) params.get("key");
		if (!StringUtils.isEmpty(key)) {
			queryWrapper.and((wrapper) -> {
				wrapper.eq("sku_id", key).or().like("sku_name", key);
			});
		}

		String catelogId = (String) params.get("catelogId");
		if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {

			queryWrapper.eq("catalog_id", catelogId);
		}

		String brandId = (String) params.get("brandId");
		if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(catelogId)) {
			queryWrapper.eq("brand_id", brandId);
		}

		String min = (String) params.get("min");
		if (!StringUtils.isEmpty(min)) {
			queryWrapper.ge("price", min);
		}

		String max = (String) params.get("max");

		if (!StringUtils.isEmpty(max)) {
			try {
				BigDecimal bigDecimal = new BigDecimal(max);

				if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
					queryWrapper.le("price", max);
				}
			} catch (Exception e) {

			}

		}


		IPage<SkuInfoEntity> page = this.page(
				new Query<SkuInfoEntity>().getPage(params),
				queryWrapper
		);

		return new PageUtils(page);
	}

	@Override
	public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
		List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
		return list;
	}

	@Override
	public SkuItemVo item(Long skuId) {
		SkuItemVo skuItemVo = new SkuItemVo();

		// 1.查询sku基本信息获取 pms_sku_info
		CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
			SkuInfoEntity info = getById(skuId);
			skuItemVo.setInfo(info);
			return info;
		}, executor);
		// 3.获取sku 对应的 spu 的所有销售属性组合
		CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
			List<SkuItemSaleAttrVo> skuItemVoList = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
			skuItemVo.setSaleAttr(skuItemVoList);
		}, executor);
		// 4.获取sku 对应的 spu 的商品介绍 pms_spu_info_desc
		CompletableFuture<Void> despFuture = infoFuture.thenAcceptAsync((res) -> {
			SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
			skuItemVo.setDesp(spuInfoDescEntity);
		}, executor);
		// 5.获取sku 对应的 spu 的规格参数信息
		CompletableFuture<Void> groupAttrFuture = infoFuture.thenAcceptAsync((res) -> {
			List<SpuItemAttrGroupVo> attrGroupVoList = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
			skuItemVo.setGroupAttrs(attrGroupVoList);
		}, executor);

		// 2.查询sku的图片信息
		CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
			List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
			skuItemVo.setImages(images);
		}, executor);

		// 查询 本商品是否有参与秒杀活动
		CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
			R r = seckillFeignService.getSkuSeckillInfo(skuId);
			if (r.getCode() == 0) {
				SeckillInfoVo data = r.getData(new TypeReference<SeckillInfoVo>() {
				});
				skuItemVo.setSeckillInfoVo(data);
			}
		}, executor);

		try {
			CompletableFuture.allOf(saleAttrFuture, despFuture, groupAttrFuture, imgFuture, secKillFuture).get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return skuItemVo;
	}

	@Override
	public Map<Long, BigDecimal> getProductPrices(List<Long> skuIds) {
		SkuInfoDao baseMapper = this.baseMapper;
		List<SkuInfoEntity> skuInfoEntities = baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().in("sku_id", skuIds));
		Map<Long, BigDecimal> prices = skuInfoEntities.stream().collect(Collectors.toMap(SkuInfoEntity::getSkuId, SkuInfoEntity::getPrice));
		return prices;
	}

}
